package trabalho.doo3.j2me.telas;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import trabalho.doo3.j2me.bean.Filme;
import trabalho.doo3.j2me.bean.Reserva;
import trabalho.doo3.j2me.midlet.Midlet;

/**
 *
 * @author Matheus
 */
public class TelaReservas extends List implements CommandListener {

    private Midlet mid;
    private Command btVoltar;
    private Command btRemover;
    private Command btFilmes;
    private Filme f;
    private String login;
    private Reserva r;
    private Vector v;
    private String URL = "http://localhost:8080/Trabalho_DOO_III_-_Web_Server/servlet";

    public TelaReservas(String title, Midlet mid, String login) {
        super(title, List.EXCLUSIVE);
        this.mid = mid;
        this.login = login;
        this.btVoltar = new Command("Logout", Command.BACK, 0);
        this.btFilmes = new Command("Filmes", Command.ITEM, 1);
        this.btRemover = new Command("Remover", Command.ITEM, 2);
        this.addCommand(btVoltar);
        this.addCommand(btFilmes);
        this.addCommand(btRemover);
        inicializa();
        this.setCommandListener(this);
    }

    public void commandAction(Command c, Displayable d) {
        Display display = Display.getDisplay(mid);
        if (c == btFilmes) {
            conexaoWWW();
            display = Display.getDisplay(mid);
            TelaFilmes telaLogin = new TelaFilmes("Tela de filmes", mid, login);
            display.setCurrent(telaLogin);
        } else if (c == btRemover) {
            try {            
                r.open();
                r.setId(Integer.parseInt(this.getString(this.getSelectedIndex()).substring(0, 1)));
                r.setFilme_id(this.getString(this.getSelectedIndex()).substring(4).trim());
                r.setDeletar("sim");
                addReserva(r);
                r.delete(r);
                r.close();
                delete(this.getSelectedIndex());
            } catch (RecordStoreNotOpenException ex) {
                ex.printStackTrace();
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
            }
        } else if (c == btVoltar) {
            try {
                r.open();
                Vector todos = r.todos();
                for (int i = 0; i < todos.size(); i++) {
                    Reserva listaBean = (Reserva) todos.elementAt(i);
                    addReserva(listaBean);
                }
                r.close();
                r.clear();
            } catch (RecordStoreNotOpenException ex) {
                ex.printStackTrace();
            } catch (InvalidRecordIDException ex) {
                ex.printStackTrace();
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            display = Display.getDisplay(mid);
            TelaLogin telaLogin = new TelaLogin("Tela de Login", mid);
            display.setCurrent(telaLogin);
        }
    }

    private void conexaoWWW() {
        HttpConnection httpConn = null;
        try {
            httpConn = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
            httpConn.setRequestMethod(HttpConnection.POST);
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
            httpConn.setRequestProperty("Content-Language", "pt-BR");
            httpConn.setRequestProperty("Accept", "application/octet-stream");
            httpConn.setRequestProperty("Connection", "close");
            OutputStream os = httpConn.openOutputStream();
            String l = "&usuario=" + login;
            os.write("acao=filme".getBytes());
            os.write(l.getBytes());
            os.close();
            String msg = httpConn.getResponseMessage();
            int code = httpConn.getResponseCode();
            if (code == httpConn.HTTP_OK) {
                DataInputStream dis = httpConn.openDataInputStream();
                String leitura = null;
                f = new Filme();
                try {
                    f.clear();
                } catch (RecordStoreException ex) {
                    ex.printStackTrace();
                }
                do {
                    leitura = dis.readUTF();
                    if (!"#Encerra leitura#".equals(leitura)) {
                        f.setNome(leitura);
                        f.setId(dis.readInt());
                        try {
                            f.open();
                            f.update(f);
                            f.close();
                        } catch (RecordStoreException ex) {
                            try {
                                f.insert(f);
                                f.close();
                            } catch (RecordStoreException ex1) {
                                ex1.printStackTrace();
                            }
                        }
                    }
                } while (!"#Encerra leitura#".equals(leitura) && leitura != null);
                dis.close();
            } else {
                System.out.println("Código invalido: " + msg);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void inicializa() {
        deleteAll();
        try {
            r = new Reserva();
            r.open();
            Vector todos = r.todos();
            for (int i = 0; i < todos.size(); i++) {
                Reserva listaBean = (Reserva) todos.elementAt(i);
                append(listaBean.getId() + " - " + listaBean.getFilme_id(), null);
            }
            r.close();
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (InvalidRecordIDException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void addReserva(Reserva reserva) {
        HttpConnection httpConn = null;
        try {
            httpConn = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
            httpConn.setRequestMethod(HttpConnection.POST);
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
            httpConn.setRequestProperty("Content-Language", "pt-BR");
            httpConn.setRequestProperty("Accept", "application/octet-stream");
            httpConn.setRequestProperty("Connection", "close");
            OutputStream os = httpConn.openOutputStream();
            String filme = "&filme=" + reserva.getFilme_id();
            String user = "&usuario=" + login;
            String deletar = "&deletar=" + reserva.getDeletar();
            os.write("acao=insert_reserva".getBytes());
            os.write(filme.getBytes());
            os.write(user.getBytes());
            os.write(deletar.getBytes());
            os.close();
            String msg = httpConn.getResponseMessage();
            int code = httpConn.getResponseCode();
            System.out.println(code);
            os.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
